/**
 * @author yxw
 * date : 2013年10月9日 下午9:40:55 
 */
package com.tzinfo.tzt.activity.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.MyApplication;
import com.tzinfo.tzt.util.FileTools;

/**
 * 
 * @author yxw ImageAdapter用于异步加载图片
 * 
 */
public class ImageBitmapAdapter extends BaseAdapter {
	private List<Map<String, Object>> data;
	private Context context;
	private int layoutId;
	private String[] sNmaes;
	private int[] ids;
	private LayoutInflater inflater;
	private List<Map<String, Object>> viewsData;

	public ImageBitmapAdapter(Context context, List<Map<String, Object>> data,
			int layoutId, String[] sNmaes, int[] ids) {
		this.context = context;
		this.data = data;
		this.layoutId = layoutId;
		this.sNmaes = sNmaes;
		this.ids = ids;
		this.inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		if (convertView == null) {
			convertView = inflater.inflate(layoutId, parent, false);
		}
		if(position==0){
			viewsData=new ArrayList<Map<String,Object>>();
		}
		for (int i = 0; i < sNmaes.length; i++) {

			View v = convertView.findViewById(ids[i]);
			Object dataTemp = data.get(position).get(sNmaes[i]);
			if (v instanceof Checkable) {
				if (dataTemp instanceof Boolean) {
					((Checkable) v).setChecked((Boolean) dataTemp);
				} else if (v instanceof TextView) {
					if (dataTemp != null && !"".equals((String) dataTemp)) {
						((TextView) v).setText((String) dataTemp);
					} else {
						((TextView) v).setText("暂无");
					}

				} else {
					throw new IllegalStateException(v.getClass().getName()
							+ " should be bound to a Boolean, not a "
							+ (data == null ? "<unknown type>"
									: data.getClass()));
				}

			} else if (v instanceof TextView) {
				if (dataTemp != null && !"".equals((String) dataTemp)) {
					((TextView) v).setText((String) dataTemp);
				} else {
					((TextView) v).setText("暂无");
				}
			} else if (v instanceof ImageView) {
				LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
						MyApplication.widthPixels / 5,
						MyApplication.widthPixels / 5);
				params.setMargins(10, 10, 0, 10);
				((ImageView) v).setLayoutParams(params);
				if (dataTemp instanceof Integer) {
					int n = Integer.parseInt(dataTemp.toString());
					if (n == R.drawable.point_null) {
						params = new LinearLayout.LayoutParams(0, 0);
					}
					((ImageView) v).setLayoutParams(params);
					((ImageView) v).setImageResource(Integer.parseInt(dataTemp
							.toString()));
				} else {
					try {
						int n = Integer.parseInt(dataTemp.toString());
						if (n == R.drawable.point_null) {
							params = new LinearLayout.LayoutParams(0, 0);
						}
						((ImageView) v).setLayoutParams(params);
						((ImageView) v).setImageResource(Integer
								.parseInt(dataTemp.toString()));
					} catch (NumberFormatException nfe) {
						if (dataTemp instanceof BitmapDrawable) {
							BitmapFactory.Options option = new BitmapFactory.Options();
							Bitmap bp=((BitmapDrawable) dataTemp).getBitmap();
							option.inSampleSize = FileTools.getInSampleSize(
									bp,
									MyApplication.widthPixels / 5);
							params = new LinearLayout.LayoutParams(
									MyApplication.widthPixels / 5,
									MyApplication.widthPixels / 5);
							params.setMargins(10, 10, 0, 10);
							((ImageView) v).setLayoutParams(params);
							
							((ImageView) v).setImageBitmap(bp);
						}else if(dataTemp instanceof Bitmap){
							BitmapFactory.Options option = new BitmapFactory.Options();
							Bitmap bp=((Bitmap) dataTemp);
							option.inSampleSize = FileTools.getInSampleSize(
									bp,
									MyApplication.widthPixels / 5);
							params = new LinearLayout.LayoutParams(
									MyApplication.widthPixels / 5,
									MyApplication.widthPixels / 5);
							params.setMargins(10, 10, 0, 10);
							((ImageView) v).setLayoutParams(params);
							((ImageView) v).setImageBitmap(bp);
						}else if(dataTemp instanceof String){
							((ImageView) v).setImageDrawable(context.getResources().getDrawable(R.drawable.ic_stub));
							Map<String, Object> map=new HashMap<String, Object>();
							map.put("path", (String) dataTemp);
							map.put("image", (ImageView) v);
							viewsData.add(map);
						}
					}

				}
			} else {
				throw new IllegalStateException(v.getClass().getName()
						+ " is not a "
						+ " view that can be bounds by this SimpleAdapter");
			}
		}
		//循环结束后启动图片加载线程（）
		if(position==getCount()-1){
			new Thread(new MyRunnable(viewsData)).start();
		}
		return convertView;
	}

	private void setImage(Bitmap bitmap, ImageView imageView) {
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				MyApplication.widthPixels / 5,
				MyApplication.widthPixels / 5);
		params.setMargins(10, 10, 0, 10);
		imageView.setLayoutParams(params);
		imageView.setImageBitmap(bitmap);
	}

	class MyRunnable implements Runnable {
		List<Map<String, Object>> views;

		public MyRunnable(List<Map<String, Object>> viewsData) {
			this.views = viewsData;
		}

		@Override
		public void run() {
			for (int i = 0; i < views.size(); i++) {
				Message msg = handler.obtainMessage();
				Map<String, Object> map=views.get(i);
				String path=(String)map.get("path");
				Bitmap bitmap = BitmapFactory.decodeFile(path);
				if (bitmap != null) {
					BitmapFactory.Options option = new BitmapFactory.Options();
					option.inSampleSize = FileTools.getInSampleSize(bitmap,
							MyApplication.widthPixels / 5);
					bitmap.recycle();
					bitmap = BitmapFactory.decodeFile(path, option);
				}
				Map<String, Object> map2=new HashMap<String, Object>();
				map2.put("bitmap", bitmap);
				map2.put("image", (ImageView)map.get("image"));
				msg.arg1 = 1;
				msg.obj = map2;
				handler.sendMessage(msg);
			}

		}

	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case 1:
				Map<String, Object> map = (Map<String, Object>) msg.obj;
				setImage((Bitmap) map.get("bitmap"), (ImageView) map.get("image"));
				break;
			}
		}
	};
}